package top.itaso.lib.net.rtf2;


import android.text.TextUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import top.itaso.lib.net.ConfigKeys;
import top.itaso.lib.net.NetInit;
import top.itaso.lib.net.callback.IInterceptorParamsSet;
import top.itaso.lib.net.log.LogUtils;

/**
 * @Description: 根据应用层实现的 IInterceptorParamsSet -> headParams 集合进行自动追加请求头参数
 * 其中，如果该 key 已存在，则不进行覆盖（默认认为其他拦截器已经重新处理过该 key-value）
 * @Author itsdf07
 * @E-Mail 923255742@qq.com
 * @Github https://github.com/itsdf07
 * @Date 2020/11/3
 */
class HeadInterceptor implements Interceptor {
    private static final String TAG = HeadInterceptor.class.getSimpleName();

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        // HeadInterceptor intercept: 原始请求 Request 中的 header={}
        LogUtils.logd(TAG + " intercept: 原始请求 Request 中的 header={" + requestHeaders2Log(request) + "}");

        IInterceptorParamsSet interceptorParamsSet = NetInit.getConfiguration(ConfigKeys.INTERCEPTOR_PARAMS_SET.name());
        if (interceptorParamsSet == null) {
            return chain.proceed(request);
        }
        HashMap<String, String> headerParams = interceptorParamsSet.headerParams();
        if (headerParams == null) {
            return chain.proceed(request);
        }

        final Request.Builder newRequestBuilder = request.newBuilder();

        StringBuilder commonHeaders = new StringBuilder();
        Iterator iterator = headerParams.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            if (entry == null || entry.getKey() == null || entry.getValue() == null) {
                continue;//数据不正常时跳过
            }
            String key = entry.getKey().toString();
            if (!TextUtils.isEmpty(request.headers().get(key))) {
                continue;//追加头已经在存在，则跳过
            }
            String value = entry.getValue().toString();
            newRequestBuilder.addHeader(key, value);
            if (LogUtils.isLog()) {
                commonHeaders.append(key + "=" + value + ",");
            }
        }
        // HeadInterceptor intercept: 通过 IInterceptorParamsSet 设置的 headerParams 参数={pkgName=top.itaso.app,channel=00001,clientOs=1,version=1.0,}
        LogUtils.logd(TAG + " intercept: 通过 IInterceptorParamsSet 设置的 headerParams 参数={" + commonHeaders.toString() + "}");

        Request newRequest = newRequestBuilder.build();
        // HeadInterceptor intercept: 新构建的 Request 中的 header={channel=[00001],clientos=[1],pkgname=[top.itaso.app],version=[1.0],}
        LogUtils.logd(TAG + " intercept: 新构建的 Request 中的 header={" + requestHeaders2Log(newRequest) + "}");

        Response response = chain.proceed(newRequest);
        // HeadInterceptor intercept: response.code=200
        LogUtils.logd(TAG + " intercept: response.code=" + response.code());
        return response;
    }

    private String requestHeaders2Log(Request request) {
        if (!LogUtils.isLog()) {
            return "";
        }
        Iterator requestIteratorHeader = request.headers().toMultimap().entrySet().iterator();
        StringBuilder requestHeaders = new StringBuilder();
        while (requestIteratorHeader.hasNext()) {
            Map.Entry entry = (Map.Entry) requestIteratorHeader.next();
            if (entry == null || entry.getKey() == null || entry.getValue() == null) {
                continue;//数据不正常时跳过
            }
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            requestHeaders.append(key + "=" + value + ",");
        }
        return requestHeaders.toString();
    }
}
